﻿/**
 * @file maincontroller.cpp
 * @author huangxb
 * @email 18228033207@163.com
 * @date 2025-04-08
 * @brief 主窗口视图控制器.
 */
#include "mainwindow.h"
#include "maincontroller.h"
#include "button/buttonsviewwidget.h"
#include "lineedit/lineeditcontainerwidget.h"
#include "GIF/gifview.h"
#include "GIF/gifviewcontroller.h"
#include "table/tablecontainerwidget.h"
#include "window/windowcontainerwidget.h"
#include <QStandardItemModel>

CMainController::CMainController(QObject *parent)
    : QObject{parent}
{

}

void CMainController::SetView(MainWindow *pView)
{
    m_pMainView = pView;
}

void CMainController::InitComponentModel()
{
    if(m_pComponentModel)
    {
        delete m_pComponentModel;
        m_pComponentModel = nullptr;
    }

    m_pComponentModel = new QStandardItemModel(this);
    m_pComponentModel->setColumnCount(Column_Count);
    m_pComponentModel->setHorizontalHeaderLabels(QStringList() << tr("Component"));

    struct Components
    {
        QString strName;
        ComponentType eType;
    };
    QVector<Components> vecComponent;
    vecComponent.push_back({tr("Button"), Component_Button});
    vecComponent.push_back({tr("LineEdit"), Component_LineEdit});
    vecComponent.push_back({tr("GIF"), Component_Gif});
    vecComponent.push_back({tr("Table"), Component_Table});
    vecComponent.push_back({tr("Window"), Component_Window});

    int nRow = 0;
    foreach(auto comp, vecComponent)
    {
        auto pItem = new QStandardItem(comp.strName);
        pItem->setData(comp.eType, DataRole_Component);
        pItem->setEditable(false);
        m_pComponentModel->setItem(nRow++, Column_Name, pItem);
    }
}

QStandardItemModel *CMainController::GetComponentModel()
{
    return m_pComponentModel;
}

void CMainController::DoubleClickComponent(const QModelIndex &index)
{
    if(!m_pMainView)
    {
        return;
    }
    auto data = m_pComponentModel->data(index, DataRole_Component);
    if(!data.isValid())
    {
        return;
    }
    auto nComponentType = data.toInt();
    QWidget* pView = nullptr;
    switch (nComponentType) {
    case Component_Button:
        pView = new CButtonsViewWidget();
        break;
    case Component_LineEdit:
        pView = new CLineEditContainerWidget;
        break;
    case Component_Gif:
    {
        m_spGIFController.reset(new CGIFViewController);
        CGIFView* pGIFView = new CGIFView();

        m_spGIFController->SetView(pGIFView);
        pGIFView->SetController(m_spGIFController.get());

        pView = pGIFView;
        break;
    }
    case Component_Table:
        pView = new CTableContainerWidget;
        break;
    case Component_Window:
        pView = new CWindowContainerWidget;
        break;
    default:
        break;
    }

    m_pMainView->ShowComponentView(pView);
}
